from rest_framework import serializers
import re

from apps.users.models import User

# 操作和模型类相关数据内容,继承ModelSerializer
class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ["id","username","mobile","email"]



class UserAddSerializer(serializers.ModelSerializer):
    # 第一种约束方法
    # username = serializers.CharField(max_length=20,min_length=5)
    # password = serializers.CharField(max_length=20,min_length=8,write_only=True)
    class Meta:
        model = User
        fields = ["username","password","mobile","email"]
        # 第二种约束方法  extra_kwargs
        extra_kwargs = {
            # 字段名: { 选项名: value }
            "username":{
                "max_length":20,
                "min_length":5
            },
            "password":{
                "max_length":20,
                "min_length":8,
                "write_only":True
            }
        },

    # 验证手机号格式
    def validate_mobile(self, attrs):
        """
        :param attrs: 获取手机号值
        :return:
        """
        if re.match(r"1[3-9]\d{9}", attrs):
            raise serializers.ValidationError("手机号格式不正确")
        return attrs

    # 由于密码是明文,所以要重写create方法 create_user自动帮我们加密
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
